<template>
  <div
    class="flex h-100% ml-20px"
    style="background-color: #fff; border-radius: 10px"
  >
    <!-- 设备树组件 -->
    <div>
      <div class="flex ml-15px mt-15px">
        <BaseButton type="primary" @click="exportActionExcel">
          下载模板
        </BaseButton>
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"
          :accept="'.xlsx,.xls'"
          :on-change="(file) => handleFileSelect(file)"
        >
          <BaseButton class="opBtn mx-12px" size="" type="primary"
            >导入数据</BaseButton
          >
        </el-upload>
      </div>

      <DepartmentTree ref="departmentTreeRef" @node-change="currentChange" />
    </div>
    <!-- 右侧内容区域 -->
    <div
      class="tableManage"
      style="width: calc(100% - var(--left-tree-max-width))"
    >
      <ContentWrap class="ml-10px flex flex-col justify-end">
        <!-- 操作按钮区域 -->
        <div class="mb-27px">
          <BaseButton type="primary" @click="AddAction('新增工程')">
            新增工程
          </BaseButton>
          <BaseButton type="primary" @click="AddAction('新增节点')">
            新增节点
          </BaseButton>
          <BaseButton :loading="delLoading" type="danger" @click="delData()">
            删除
          </BaseButton>
        </div>
        <ElDivider />

        <!-- 主表单区域 -->
        <Form
          :rules="rules"
          :model="formTotalData"
          @register="formRegister"
          :schema="filtersSchema"
          :key="formKey"
        />
        <ElDivider />

        <!-- 保存按钮 -->
        <div class="flex justify-end mr-30px">
          <BaseButton type="primary" @click="save">保存</BaseButton>
        </div>
      </ContentWrap>
    </div>

    <!-- 新增对话框 -->
    <Dialog
      :width="dialogVisible && dialogTitle === '新增工程' ? '500px' : '600px'"
      v-model="dialogVisible"
      :title="dialogTitle"
      ref="dialogFormRef"
    >
      <!-- 工程表单 -->
      <Form
        width="350px"
        v-if="dialogTitle === '新增工程'"
        :schema="dialogEngineeringSchema"
        @register="dialogFormEngineerRegister"
      />

      <!-- 节点表单 -->
      <Form
        v-else
        :schema="filtersDialogSchema"
        @register="dialogFormDeviceRegister"
        :key="dialogFormKey"
      />

      <!-- 对话框底部按钮 -->
      <template #footer>
        <BaseButton
          type="primary"
          :loading="dialogSaveLoading"
          @click="handleDialogSave"
        >
          保存
        </BaseButton>
        <BaseButton @click="dialogVisible = false">关闭</BaseButton>
      </template>
    </Dialog>
    <Dialog v-model="resultDialogVisible" :title="importTitle" width="50%">




        <div class="import-result" >
          <div
            class="import-result-container"
            :style="{ height: resultContainerHeight }"
          >

            <div
             v-for="(error, index) in tabs1"
                :key="index"
              class="demo-tabs full-height-tabs"
            >

                <!-- 移除外层的 flex 布局，使用简单的固定高度 -->
                <div class="error-content-wrapper">

                    <div
                      class="error-item"

                    >
                      <h4 class="mb-10px">{{ error.dataRow }}:</h4>
                      <p
                        class="mb-5px"
                        v-for="(item, i) in error.errors"
                        :key="i"
                      >
                        {{ item }}
                      </p>
                    </div>


                </div>

            </div>
          </div>
        </div>


      <template #footer>
        <BaseButton type="primary" @click="resultDialogVisible = false">
          确定
        </BaseButton>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="tsx">
import { ContentWrap } from "@/components/ContentWrap";
import { directAxios } from "@/axios/index";
import { getDictionary } from "@/utils/options";
import {
  ref,
  unref,
  nextTick,
  watch,
  reactive,
  onMounted,
  computed,
  watchEffect,
} from "vue";
import { Form, FormSchema } from "@/components/Form";
import DepartmentTree from "@/components/DepartmentTree/index.vue";
import {
  ElTree,
  ElDivider,
  ElMessageBox,
  ElMessage,
  ElUpload,
  UploadFile,
  UploadInstance,
} from "element-plus";
import { useForm } from "@/hooks/web/useForm";
import type {
  DepartmentItem,
  DepartmentUserItem,
} from "@/components/DepartmentTree/types";

import { Dialog } from "@/components/Dialog";
import { useValidator } from "@/hooks/web/useValidator";
import { BaseButton } from "@/components/Button";
import { useDeviceTreeStore } from "@/store/modules/deviceTreeStore";

// ============ 初始化和Store定义 ============
const { required } = useValidator();

const departmentTreeRef = ref();
const deviceTreeStore = useDeviceTreeStore();

// ============ 响应式数据定义 ============

// 组件引用
const dialogFormRef = ref();
const treeEl = ref<typeof ElTree>();

// 状态数据
const departmentOptions = ref<{ label: string; value: string }[]>([]);
const currentDepartment = ref(deviceTreeStore.currentDepartment);
const currentNodeKey = ref();
const formTotalData = ref<DepartmentItem>();
const departmentList = ref<DepartmentItem[]>([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const currentRow = ref<DepartmentUserItem>();

// 加载状态
const saveLoading = ref(false);
const dialogSaveLoading = ref(false);
const delLoading = ref(false);

// 表单重新渲染key
const formKey = ref(0);
const dialogFormKey = ref(0);

// 表单数据
const dialogFormData = reactive({});
const field2Value = ref(""); // 主表单节点类型值
const field2Value1 = ref(""); // 对话框表单节点类型值
const agreementNumber = ref(""); // 协议书
// ============ 字典数据 ============
// 添加响应式高度控制
const resultContainerHeight = ref("400px"); // 默认高度
const errorContentHeight = ref("300px"); // 错误内容区域高度

const calculateHeights = () => {
  const windowHeight = window.innerHeight;
  const dialogHeight = windowHeight * 0.7;
  resultContainerHeight.value = `${dialogHeight - 120}px`;
  errorContentHeight.value = `${dialogHeight - 250}px`; // 调整这个值，为 tabs 头部留出空间
};
/**
 * 节点类型选项配置
 */
const nodeTypeOptions = ref<any[]>([
  // { label: "工程", value: "工程" },
  // { label: "系统", value: "系统" },
  // { label: "子系统", value: "子系统" },
  // { label: "设备型号", value: "设备型号" },
]);

/**
 * 获取节点类型字典数据
 */
const getNodeTypeDic = async () => {
  // 可以从后端API获取字典数据
  nodeTypeOptions.value = await getDictionary("NODE_TYPE");
};

// ============ 监听器 ============

/**
 * 监听store中的当前节点键变化
 */
watchEffect(() => {
  const nodeKey = deviceTreeStore.currentNodeKey;
  if (nodeKey !== undefined && nodeKey !== null) {
    currentNodeKey.value = nodeKey;
  }
});
/**
 * 监听当前部门变化，用于树过滤
 */
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val);
  }
);

/**
 * 监听store中的当前树节点变化，更新表单数据
 */
watch(
  () => deviceTreeStore.currentTreeNode,
  async (newNode) => {
    try {
      if (newNode) {
        formTotalData.value = { ...newNode };
        await nextTick();
        await setFormValues(newNode);
      }
    } catch (error) {
      console.error('Error in tree node watcher:', error);
      // 可以选择显示用户友好的错误信息
      ElMessage.error('加载节点数据失败');
    }
  },
  { deep: true }
)

/**
 * 监听节点类型选项变化，更新对话框表单选项
 */
// watch(nodeTypeOptions, (newOptions) => {
//   dialogDeviceSchema[1].componentProps.options = newOptions;
// });

// ============ 表单Schema定义 ============

// 表单验证规则
const rules = reactive({
  // 可以添加具体的验证规则
  // realName: [required(), maxlength(50)],
  // phoneNumber: [phone()],
  // email: [email()]
});

/**
 * 主表单基础字段配置
 */
const companyOptions = ref<any[]>([]);
const formSchema = reactive<FormSchema[]>([
  // {
  //   field: "deviceName",
  //   label: "设备名称（型号）",
  //   component: "Input",
  //   formItemProps: { rules: [required()] },
  //   value: formTotalData.value?.deviceName || "",
  // },
  {
    field: "nodeType",
    label: "节点类型",
    component: "Input",
    formItemProps: { rules: [required()] },
    componentProps: {
      // options: nodeTypeOptions,
      disabled: true,
      modelValue: field2Value,
      "onUpdate:modelValue": (val) => {
        field2Value.value = val;
        // 非设备类型时清空相关字段
        if (val !== "设备型号") {
          setValues({
            superiorSubsystem: "",
            agreementNumber: "",
            deviceModel: "",
            importantLevel: "",
            deviceCount: "",
            manufacturer: "",
            supervisorContact: "",
          });
        }
      },
    },
    value: formTotalData.value?.nodeType || "",
  },
]);

/**
 * 动态表单字段配置（设备类型特有字段）
 */
// const dynamicFormSchema = ref<FormSchema[]>([
//   {
//     field: "superiorSystem",
//     label: "上级系统",
//     component: "Input",
//     value: formTotalData.value?.superiorSystem || "",
//   },
//   {
//     field: "superiorSubsystem",
//     label: "上级分系统",
//     component: "Input",
//     value: formTotalData.value?.superiorSubsystem || "",
//   },
//   {
//     field: "agreementNumber",
//     label: "协议书编号",
//     component: "Input",
//     value: formTotalData.value?.agreementNumber || "",
//   },
//   {
//     field: "deviceModel",
//     label: "设备型号",
//     component: "Input",
//     value: formTotalData.value?.deviceModel || "",
//   },
//   {
//     field: "importantLevel",
//     label: "机载设备重要度类别",
//     component: "Select",
//     value: formTotalData.value?.importantLevel || "",
//        optionApi: async () => {
//         const res = await getDictionary("IMPORTANT_LEVEL")
//         return res
//       }
//   },
//   {
//     field: "deviceCount",
//     label: "单架安装设备数量",
//     component: "Input",
//     value: formTotalData.value?.deviceCount || "",
//   },
//   {
//     field: "manufacturer",
//     label: "机载设备承制单位",
//     component: "Input",
//     value: formTotalData.value?.manufacturer || "",
//   },
//   {
//     field: "supervisorContact",
//     label: "机载设备主管/联系电话",
//     component: "Input",
//     value: formTotalData.value?.supervisorContact || "",
//   },
// ]);
// 选择协议书
const agreementFormSchema = ref<FormSchema[]>([
  {
    field: "agreementNumber",
    label: "协议书编号",
    component: "Input",
     formItemProps: {
        rules: [
          { required: true, message: "请输入协议书编号" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入协议书编号" },
        ],
      },
    value: formTotalData.value?.agreementNumber || "",
  },
  {
    field: "deviceName",
    label: "设备名称",
    component: "Input",
    formItemProps: {
        rules: [
          { required: true, message: "请输入设备名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入设备名称" },
        ],
      },
    value: formTotalData.value?.deviceName || "",
  },
  {
    field: "superiorSystem",
    label: "上级系统",
    component: "Input",
    componentProps: {
      disabled: true,
    },
      formItemProps: {
        rules: [
          { required: true, message: "请输入上级系统" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入上级系统" },
        ],
      },
    value: formTotalData.value?.superiorSystem ||  "",
  },
  {
    field: "importantLevel",
    label: "机载设备重要度类别",
    component: "Select",
      formItemProps: {
        rules: [
          { required: true, message: "请输入机载设备重要度类别" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入机载设备重要度类别" },
        ],
      },
    value: formTotalData.value?.importantLevel || "",
    optionApi: async () => {
      const res = await getDictionary("IMPORTANT_LEVEL");
      return res;
    },
  },
  {
    field: "manufacturer",
    label: "机载设备承制单位",
    component: "Select",
    formItemProps: { rules: [required()] },
    value: formTotalData.value?.manufacturer || "",
    componentProps: {
      filterable: true,
      placeholder: "请输入机载设备承制单位",
    },
    optionApi: async () => {
      const res = await "/api/deviceManufacturer/list".get();
      companyOptions.value = res.data?.map((v: any) => ({
        label: v.name,
        value: v.code,
      }));
      return res.data?.map((v: any) => ({
        label: v.name,
        value: v.code,
      }));
    },
  },
  {
    field: "supervisorContact",
    label: "机载设备主管/联系电话",
    formItemProps: {
        rules: [
          { required: true, message: "请输入机载设备主管/联系电话" },

        ],
      },
    component: "Input",
    value: formTotalData.value?.supervisorContact || "",
  },
]);
const dynamicFormSchema = ref<FormSchema[]>([
  {
    field: "deviceModel",
    label: "设备型号",
    component: "Input",
    formItemProps: {
        rules: [
          { required: true, message: "请输入设备型号" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入设备型号" },
        ],
      },
    value: formTotalData.value?.deviceModel || "",
  },
  {
    field: "deviceName",
    label: "设备名称",
    component: "Input",
    formItemProps: {
        rules: [
          { required: true, message: "请输入设备名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入设备名称" },
        ],
      },
    value: formTotalData.value?.deviceName || "",
  },
  {
    field: "manufacturer",
    label: "成品厂名称",
    component: "Select",
    formItemProps: {
        rules: [
          { required: true, message: "请输入成品厂名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入成品厂名称" },
        ],
      },
    value: formTotalData.value?.manufacturer || "",
    componentProps: {
      filterable: true,
      placeholder: "请输入单位名称",
    },
    optionApi: async () => {
      const res = await "/api/deviceManufacturer/list".get();
      companyOptions.value = res.data?.map((v: any) => ({
        label: v.name,
        value: v.code,
      }));
      return res.data?.map((v: any) => ({
        label: v.name,
        value: v.code,
      }));
    },
  },

  //  form: {
  //     component: "Select",
  //     value: [],
  //     formItemProps: {
  //       rules: [
  //         { required: true, message: "请输入单位名称" },
  //         { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入单位名称" },
  //       ],
  //     },

  // },
  {
    field: "agreementNumber",
    label: "协议书编号",
    component: "Input",
     componentProps: {

      disabled: true,
     },
    formItemProps: {
        rules: [
          { required: true, message: "请输入协议书编号" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入协议书编号" },
        ],
      },
    value: formTotalData.value?.agreementNumber || "",
  },

  {
    field: "deviceCount",
    label: "单架安装设备数量",


      component: "InputNumber",
      formItemProps: {
        rules: [
          { required: true, message: "请输入单架安装设备数量" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },

    value: formTotalData.value?.deviceCount || "",
  },
]);
const otherFormSchema1 = ref<FormSchema[]>([
  {
    field: "deviceName",
    label: "工程名称",
    component: "Input",
     formItemProps: {
        rules: [
          { required: true, message: "请输入工程名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入工程名称" },
        ],
      },
    value: formTotalData.value?.deviceName || "",
  },
]);
const otherFormSchema2 = ref<FormSchema[]>([
  {
    field: "deviceName",
    label: "系统名称",
    component: "Input",
     formItemProps: {
        rules: [
          { required: true, message: "请输入系统名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入系统名称" },
        ],
      },
    value: formTotalData.value?.deviceName || "",
  },
]);
const otherFormSchema3 = ref<FormSchema[]>([
  {
    field: "deviceName",
    label: "协议书名称",
    component: "Input",
     formItemProps: {
        rules: [
          { required: true, message: "请输入协议书名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入协议书名称" },
        ],
      },
    value: formTotalData.value?.deviceName || "",
  },
]);
/**
 * 计算主表单结构（根据节点类型动态显示字段）
 */
const filtersSchema = computed(() => {
  if (field2Value.value === "设备型号") {
    return [...formSchema, ...dynamicFormSchema.value];
  } else if (field2Value.value === "协议书") {
    return [...formSchema, ...agreementFormSchema.value];
  } else if (field2Value.value === "工程") {
    return [...formSchema, ...otherFormSchema1.value];
  } else if (field2Value.value === "系统") {
    return [...formSchema, ...otherFormSchema2.value];
  } else {
    return formSchema;
  }
});




/**
 * 对话框工程表单配置
 */
const dialogEngineeringSchema = reactive<FormSchema[]>([
  {
    field: "deviceName",
    label: "工程名称",
    component: "Input",
    formItemProps: { rules: [required()] },
    colProps: { span: 24 },
  },
]);

/**
 * 对话框节点表单基础配置
 */
const dialogDeviceSchema = reactive<FormSchema[]>([
  // {
  //   field: "deviceName",
  //   label: "设备名称（型号）",
  //   component: "Input",
  //   formItemProps: { rules: [required()] },
  // },
  {
    field: "nodeType",
    label: "节点类型",
    component: "Input",
    formItemProps: { rules: [required()] },
    componentProps: {
      // options: nodeTypeOptions,
      disabled: true,
      // onChange: (val) => {
      //   field2Value1.value = val;
      // },

      modelValue: field2Value1,
      "onUpdate:modelValue": (val) => {
        field2Value1.value = val;
      },
    },
  },
]);

/**
 * 计算对话框表单结构（根据节点类型动态显示字段）
 */
const filtersDialogSchema = computed(() => {
  // 确保使用扩展运算符创建新数组，触发响应式更新
  const baseSchema = [...dialogDeviceSchema];

  if (field2Value1.value === "设备型号") {
    return [...baseSchema, ...dynamicFormSchema.value];
  } else if (field2Value1.value === "协议书") {
    return [...baseSchema, ...agreementFormSchema.value];
  } else if (field2Value1.value === "工程") {
    return [...baseSchema, ...otherFormSchema2.value];
  } else if (field2Value1.value === "系统") {
    return [...baseSchema, ...otherFormSchema2.value];
  }

  // 默认返回基础表单结构
  return baseSchema;
});

// ============ 表单Hook ============

// 主表单
const { formRegister, formMethods } = useForm();
const { getElFormExpose, setValues, getFormData } = formMethods;

// 对话框表单
const {
  formRegister: dialogFormEngineerRegister,
  formMethods: dialogFormEngineerMethods,
} = useForm();
const {
  formRegister: dialogFormDeviceRegister,
  formMethods: dialogFormDeviceMethods,
} = useForm();

// ============ 方法定义 ============

/**
 * 树节点选择变化事件处理
 * @param data 选中的节点数据
 */
const currentChange = async (data: DepartmentItem | null) => {


  if (data) {
    // 保存到store
    deviceTreeStore.setCurrentNode(data);
    currentNodeKey.value = data.deviceCode;

    // 更新表单数据
    formTotalData.value = { ...data };
    await setFormValues(data);
  } else {
    // 处理空节点情况（树为空时）
    console.log("接收到空节点，清空表单");

    // 清空表单数据
    formTotalData.value = {
      deviceName: "",
      nodeType: "",
      superiorSystem: "",
      superiorSubsystem: "",
      agreementNumber: "",
      deviceModel: "",
      importantLevel: "",
      deviceCount: "",
      manufacturer: "",
      supervisorContact: "",
      id: "",
      deviceCode: ""
    };

    // 重置表单字段值
    await setValues(formTotalData.value);
    field2Value.value = "";

    // 强制重新渲染表单
    formKey.value++;

    // 清空store中的选中状态
    deviceTreeStore.setCurrentNode(null);
    currentNodeKey.value = "";
  }
};

/**
 * 设置表单值
 * @param data 节点数据
 */
const setFormValues = async (data: DepartmentItem) => {
  try {
    await nextTick();

    const formData = {
      deviceName: data.deviceName || "",
      nodeType: data.nodeType || "",
      superiorSystem: data.superiorSystem || "",
      superiorSubsystem: data.superiorSubsystem || "",
      agreementNumber: data.agreementNumber || "",
      deviceModel: data.deviceModel || "",
      importantLevel: data.importantLevel || "",
      deviceCount: data.deviceCount || "",
      manufacturer: data.manufacturer || "",
      supervisorContact: data.supervisorContact || "",
      id: data.id || "",
    };

    await setValues(formData);
    field2Value.value = data.nodeType || "";
    formKey.value++;
  } catch (error) {
    console.error("设置表单值失败:", error);
    // 重新抛出错误以便在调用处处理
    throw error;
  }
};

/**
 * 刷新树数据
 */

const refreshTree = async () => {
  await departmentTreeRef.value?.refreshTree();
  // 刷新后检查树是否为空
  await checkAndClearFormIfTreeEmpty();
};

/**
 * 刷新根节点和树数据
 */
const refreshRootAndTree = async () => {
  try {
    await departmentTreeRef.value?.refreshRootTree();
    // 刷新后检查树是否为空
    await checkAndClearFormIfTreeEmpty();
  } catch (error) {
    console.error("刷新根节点和树失败:", error);
  }
};

/**
 * 新增操作
 * @param text 操作类型：'新增工程' | '新增节点'
 */
const AddAction = (text: string) => {
  if (text === "新增节点") {
   console.log(formTotalData.value.nodeType,formTotalData.value);


    if (currentNodeKey.value) {
      dialogVisible.value = true;
      dialogTitle.value = text;
      currentRow.value = undefined;

      // 重置对话框表单
      dialogFormData.value = {};

      dialogFormKey.value++;
      var str;
      if (formTotalData.value.nodeType === "工程") {
        str = "系统";
      } else if (formTotalData.value.nodeType === "系统") {

// superiorSystem
        str = "协议书";
      } else if (formTotalData.value.nodeType === "协议书") {
        str = "设备型号";
      } else if (formTotalData.value.nodeType === "设备型号") {
        str = "设备型号";
      }
      field2Value1.value = str;
      // 重置表单值
      nextTick(() => {
        dialogFormDeviceMethods.setValues({
          deviceName: "",
          nodeType: str,
          superiorSystem: formTotalData.value.deviceName,
          superiorSubsystem: "",
          agreementNumber: formTotalData.value.agreementNumber || "",
          deviceModel: "",
          importantLevel: "",
          deviceCount: "",
          manufacturer: "",
          supervisorContact: "",
        });
      });
    } else {
      ElMessage.error("请先选择节点");
    }
  } else {
    dialogVisible.value = true;
    dialogTitle.value = text;
    currentRow.value = undefined;

    // 重置工程表单
    nextTick(() => {
      dialogFormEngineerMethods.setValues({ deviceName: "" });
    });
  }
};

/**
 * 删除节点数据
 */
const delData = async () => {
  const currentData = deviceTreeStore.currentTreeNode;
  console.log("删除节点数据:", currentData);

  if (currentData?.id) {
    try {
      delLoading.value = true;

      await ElMessageBox.confirm("确定要删除这个节点吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });

      // const params = new URLSearchParams();
      // params.append("id", currentData.id);
      const params = {
        id: currentData.id,
      };
      const res = await directAxios.post("/dDeviceCatalog/delete", params, {
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        transformRequest: [(data) => data.toString()],
      });

      if (res.code === 200) {
        ElMessage.success("删除成功");

        // 根据节点类型刷新不同的树结构
        if (currentData.nodeType === "设备型号") {
          await nextTick();
        departmentTreeRef.value?.selectFirstNode();
          refreshTree();
        } else if (currentData.nodeType === "工程") {
           refreshTree();
          refreshRootAndTree();
          departmentTreeRef.value?.getTreeData();
        }else {
          refreshRootAndTree();
          await nextTick();
        departmentTreeRef.value?.selectFirstNode();
        }
 // 检查树是否为空，如果为空则清空表单
        await checkAndClearFormIfTreeEmpty();
        // 清空选中状态
        // deviceTreeStore.setCurrentNode(null);
        // currentNodeKey.value = "";
      } else {
        ElMessage.error(res.data.msg || "删除失败");
      }
    } catch (error) {
      if (error !== "cancel") {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    } finally {
      delLoading.value = false;
    }
  } else {
    ElMessage.error("请先选择节点");
  }
};
/**
 * 检查树是否为空，如果为空则清空表单和选中状态
 */
const checkAndClearFormIfTreeEmpty = async () => {
  await nextTick();

  // 获取当前树的数据
  const treeData = departmentTreeRef.value?.getTreeData();
  console.log("检查树数据:", treeData);

  // 如果树数据为空数组，或者第一个节点没有子节点（表示空树）
  if (!treeData || treeData.length === 0 ||
      (treeData[0] && !treeData[0].children) ||
      (treeData[0] && treeData[0].children && treeData[0].children.length === 0)) {

    console.log("检测到空树，清空表单和选中状态");

    // 清空表单数据
    formTotalData.value = {
      deviceName: "",
      nodeType: "",
      superiorSystem: "",
      superiorSubsystem: "",
      agreementNumber: "",
      deviceModel: "",
      importantLevel: "",
      deviceCount: "",
      manufacturer: "",
      supervisorContact: "",
      id: "",
      deviceCode: ""
    };

    // 重置表单字段值
    await setValues(formTotalData.value);
    field2Value.value = "";

    // 强制重新渲染表单
    formKey.value++;

    // 清空store中的选中状态
    deviceTreeStore.setCurrentNode(null);
    currentNodeKey.value = "";

    // 调用树组件的清空选中方法
    departmentTreeRef.value?.clearSelection();
  }
};
/**
 * 保存主表单数据
 */
const save = async () => {
  const elForm = await getElFormExpose();
  const valid = await elForm?.validate().catch(console.error);

  if (valid) {
    try {
      await ElMessageBox.confirm("是否确认修改?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      });

      saveLoading.value = true;
      const formData = await getFormData();
      // companyOptions.value
      console.log(123, companyOptions.value, formData);

      const submitData = {
        ...formData,
        id: formTotalData.value.id, // 确保ID不被覆盖
        manufacturerName:
          companyOptions.value.find((v) => v.value === formData.manufacturer)
            ?.label || "",
      };

      const data =
        formTotalData.value.nodeType == "设备型号"
          ? {
              ...formData,
              id: formTotalData.value.id,
              manufacturerName:
                companyOptions.value.find(
                  (v) => v.value === formData.manufacturer
                )?.label || "",
              manufacturer: formData.manufacturer,
            }
          : { ...formData, id: formTotalData.value.id };

      const res = await "/dDeviceCatalog/save".post(data);
      ElMessage.success("保存成功");

      // 更新store中的数据
      if (deviceTreeStore.currentTreeNode) {
        const updatedNode = {
          ...deviceTreeStore.currentTreeNode,
          // ...submitData,
          ...data,
        };
        deviceTreeStore.setCurrentNode(updatedNode);
      }

      // 刷新树
      refreshTree();

      // 重新设置当前选中节点，保持选中状态
      if (formTotalData.value?.deviceCode) {
        await nextTick();
        departmentTreeRef.value?.setCurrentKey(formTotalData.value.deviceCode);
      }
    } catch (error) {
      if (error !== "cancel") {
        console.error(error);
        ElMessage.error("保存失败");
      }
    } finally {
      saveLoading.value = false;
    }
  }
};

/**
 * 处理对话框保存操作
 */
const handleDialogSave = async () => {
  let valid = false;
  let formData = null;

  if (dialogTitle.value === "新增工程") {
    const elForm = await dialogFormEngineerMethods.getElFormExpose();
    valid = await elForm?.validate().catch(() => false);

    if (valid) {
      formData = await dialogFormEngineerMethods.getFormData();
      await saveDialogData({ ...formData, nodeType: "工程" }, "工程");
    }
  } else if (dialogTitle.value.trim() === "新增节点") {
    const elForm = await dialogFormDeviceMethods.getElFormExpose();
    valid = await elForm?.validate().catch(() => false);

    if (valid) {
      formData = await dialogFormDeviceMethods.getFormData();
      await saveDialogData(
        { ...formData, deviceParentCode: currentNodeKey.value },
        "节点"
      );
    } else {
      ElMessage.error("请填写必填字段");
    }
  }
};

/**
 * 保存对话框数据
 * @param formData 表单数据
 * @param type 类型：'工程' | '节点'
 */
const saveDialogData = async (formData: any, type: string) => {
  dialogSaveLoading.value = true;

  try {
    const data =
      formData.nodeType == "设备型号"
        ? {
            ...formData,
            manufacturerName:
              companyOptions.value.find(
                (v) => v.value === formData.manufacturer
              )?.label || "",
          }
        : formData;

    const res = await "/dDeviceCatalog/save".post(data);

    if (res.code === 200) {
      ElMessage.success("保存成功");
      dialogVisible.value = false;

      // 刷新树结构
      if (type === "工程") {
        await refreshRootAndTree();
      } else {
        refreshTree();
      }
    } else {
      ElMessage.error(res.data.msg || "保存失败");
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("保存失败");
  } finally {
    dialogSaveLoading.value = false;
  }
};
// 下载模板
const exportActionExcel = async () => {
  const res = await "/dDeviceCatalog/downloadExcelTemplate".get(
    {},
    {
      responseType: "blob", // 指定响应类型为blob用于文件下载
    }
  );

  if (res.status === 200) {
    // ElMessage.success("导出成功");
    await handleFileDownload(res);
    ElMessage.success("导出成功，文件已开始下载");
  } else {
    ElMessage.warning(res.data?.msg || "导出失败");
  }
};
/**
 * 处理文件下载
 * @param res 响应对象
 */
const handleFileDownload = async (res: any) => {
  const blob = new Blob([res.data], {
    type: res.headers["content-type"] || "application/octet-stream",
  });

  // 获取文件名
  const contentDisposition = res.headers["content-disposition"];
  let filename = "dataExport";
  if (contentDisposition) {
    const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
    if (filenameMatch && filenameMatch.length === 2) {
      filename = decodeURIComponent(filenameMatch[1]);
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();

  // 清理资源
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
};

// 导入相关
const resultDialogVisible = ref(false);
const uploadRef = ref<UploadInstance>();
const selectedFile = ref<File | null>(null);
const importLoading = ref(false);
const tabs1 = ref();
const activeName1 = ref("");
// 导入结果
const importResult = ref(false);
const importSuccessMessage = ref([]);
const importTitle = ref("");
/**
 * 文件选择验证
 */
const handleFileSelect = (file: UploadFile) => {
  // 验证文件类型
  if (!validateFileType(file)) {
    // 清空文件选择
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
    return false;
  }

  // 文件验证通过，继续处理
  handleFileChange(file, "data");
};
/**
 * 处理文件导入（原有的handleFileChange函数需要调整）
 */
const handleFileChange = async (file: UploadFile, type: string) => {
  console.log(file, type);

  // 这里不再需要验证，因为已经在handleFileSelect中验证过了

  ElMessageBox.confirm("该操作会覆盖当前系统下的所有型号设备树数据，确认继续？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (!file.raw) {
        return;
      }

      selectedFile.value = file.raw;
      importLoading.value = true;

      importTitle.value = "正在导入文件，请稍后...";
      try {
        tabs1.value = [];
        activeName1.value = "";
        const formData = new FormData();
 formData.append("file", file.raw);

        const res = await "/dDeviceCatalog/importTreeExcel".post(formData,{
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });
        console.log(res,678);

        if (res.code == 200) {
          ElMessage.success("导入成功");

          importResult.value = true;
          // importTitle.value = "导入成功";
          resultDialogVisible.value = false;
          // importSuccessMessage.value = res.data;
// 导入成功后刷新树组件
          // await refreshTreeAfterImport();

          refreshRootAndTree()
 refreshTree()

        } else if (res.code == 299) {
          importResult.value = false;
          importTitle.value = "导入失败";

          // 验证数据
          tabs1.value = res.data;

          resultDialogVisible.value = true;
          importLoading.value = false;
          return;
        }
      } catch (error: any) {
        console.error("导入错误:", error);
        importTitle.value = "导入失败";
        ElMessage.warning(error.data?.msg || "导入失败");
      } finally {
        importLoading.value = false;
        // 清空文件选择
        if (uploadRef.value) {
          uploadRef.value.clearFiles();
        }
        selectedFile.value = null;
      }
    })
    .catch(() => {
      // 用户取消，清空文件选择
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    });
};


/**
 * 验证文件类型
 */
const validateFileType = (file: UploadFile) => {
  if (!file.raw) {
    ElMessage.error("文件不存在");
    return false;
  }

  // 检查文件扩展名
  const fileExtension = file.name.split(".").pop()?.toLowerCase();
  const allowedExtensions = ["xls", "xlsx"];

  if (!fileExtension || !allowedExtensions.includes(fileExtension)) {
    ElMessage.error("文件格式错误！只能上传 .xlsx 或 .xls 格式的Excel文件");
    return false;
  }

  // 检查MIME类型（可选，因为不同浏览器可能识别不同）
  const allowedMimeTypes = [
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-excel.sheet.macroEnabled.12",
    "application/octet-stream", // 某些情况下可能是这个类型
  ];

  // 如果MIME类型不为空且不在允许列表中，给出警告但继续（因为扩展名正确）
  if (file.raw.type && !allowedMimeTypes.includes(file.raw.type)) {
    console.warn("文件MIME类型不匹配，但扩展名正确，继续处理");
  }

  // 限制文件大小（10MB）
  // const maxSize = 10 * 1024 * 1024; // 10MB
  // if (file.size && file.size > maxSize) {
  //   ElMessage.error('文件大小不能超过 10MB');
  //   return false;
  // }

  return true;
};

// ============ 生命周期 ============

/**
 * 组件挂载初始化
 */
onMounted(() => {
  getNodeTypeDic();
  calculateHeights();
  window.addEventListener("resize", calculateHeights);
  // 从store恢复数据
  const storedNode = deviceTreeStore.currentTreeNode;
  console.log("存储的节点数据:", storedNode);

  if (storedNode) {
    formTotalData.value = { ...storedNode };
    setFormValues(storedNode);

    nextTick(() => {
      if (storedNode.deviceCode) {
        unref(treeEl)?.setCurrentKey(storedNode.deviceCode);
      }
    });
  }
});

onUnmounted(() => {
  window.removeEventListener("resize", calculateHeights);
});
</script>

<style scoped lang="less">
:deep(.el-form-item) {
  display: flex;
  flex-direction: column !important;
}

:deep(.el-form-item__label-wrap) {
  margin-left: 0 !important;
}

:deep(.el-scrollbar) {
  height: auto !important;
}

.tree-min-width {
  min-width: 200px !important;
}

:deep(.el-tree-node__content) {
  height: 40px !important;
}

:deep(.is-current-node .el-tree-node .el-tree-node__content) {
  background-color: transparent !important;
  color: inherit !important;
  font-weight: normal;
}

:deep(.is-current-node > .el-tree-node__content) {
  background-color: var(--el-color-primary) !important;
  border-radius: 0 20px 20px 0;
  color: var(--el-tree-content-color) !important;
  font-weight: bold;
}

:deep(.el-tree) {
  background: transparent !important;
}

:deep(.el-card) {
  --el-card-bg-color: transparent !important;
  background-color: transparent !important;
}

.error-item {
  margin-bottom: 16px;
  padding: 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid rgba(251, 198, 198, 1);
  background-color: rgba(254, 240, 240, 0.5);
  // border-left: 4px solid #f56c6c;

  h4 {
    color: #f56c6c;
    font-weight: bold;
  }

  p {
    // color: #606266;
    margin: 4px 0;
    padding-left: 8px;
    color: #f56c6c;
  }
}
</style>
